/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.client.reports;

import nfse.gui.client.NetFSEClient;
import nfse.gui.client.ReportService;
import nfse.gui.client.ReportServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class StatsTab extends FlexTable {
    final FlexTable dstIPStatsTable = new FlexTable();

    final FlexTable dstPortStatsTable = new FlexTable();

    final FlexTable protocolStatsTable = new FlexTable();

    final FlexTable srcIPStatsTable = new FlexTable();

    final ListBox statsDirectionListBox = new ListBox();

    final Button statsGoButton = new Button("Go");

    final CheckBox statsIncludeTodayCheckBox = new CheckBox();

    final ListBox statsSensorListBox = new ListBox();

   //final FlexTable statsTable = new FlexTable();

    Timer statsTimer = null;

    final ListBox statsTimeRangeListBox = new ListBox();

    public StatsTab() {
        statsTimeRangeListBox.setVisibleItemCount(1);
        statsTimeRangeListBox.addItem("1 Day");
        statsTimeRangeListBox.addItem("7 Days");
        statsTimeRangeListBox.addItem("1 Month");
        statsTimeRangeListBox.addItem("3 Months");
        statsTimeRangeListBox.addItem("6 Months");
        statsTimeRangeListBox.addItem("1 Year");
        statsTimeRangeListBox.addItem("All Time");

        statsIncludeTodayCheckBox.setText("Include today");

        statsSensorListBox.addItem("Net/Sensor");

        statsDirectionListBox.setVisibleItemCount(1);
        statsDirectionListBox.addItem("All traffic");
        statsDirectionListBox.addItem("Incoming traffic");
        statsDirectionListBox.addItem("Outgoing traffic");

        statsGoButton.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                statsTimer.cancel();
                stats();
            }
        });

        FlexTable statsOptionsTable = new FlexTable();
        statsOptionsTable.setWidget(0, 0, statsTimeRangeListBox);
        statsOptionsTable.setWidget(0, 1, statsIncludeTodayCheckBox); //
        statsOptionsTable.setWidget(0, 2, statsSensorListBox);
        statsOptionsTable.setWidget(0, 2, statsDirectionListBox);
        statsOptionsTable.setWidget(0, 3, statsGoButton);

        this.setWidget(0, 0, statsOptionsTable);
        this.getFlexCellFormatter().setColSpan(0, 0, 2);
        this.setWidget(1, 0, dstIPStatsTable);
        this.getFlexCellFormatter().setWidth(0, 0, "450px");
        this.setWidget(1, 1, srcIPStatsTable); //
        this.getFlexCellFormatter().setWidth(0, 1, "500px");
        this.setWidget(2, 0, dstPortStatsTable);
        this.getFlexCellFormatter().setWidth(1, 0, "450px");
        this.setWidget(2, 1, protocolStatsTable); //
        this.getFlexCellFormatter().setWidth(1, 1, "500px");

        // stats();
        statsTimer = new Timer() {
            public void run() {
                stats();
            }
        };
    }

    private void dstIPStats() {


        ReportServiceAsync nfseService = (ReportServiceAsync) GWT.create(ReportService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.REPORT_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                FlexTable.FlexCellFormatter formatter = dstIPStatsTable.getFlexCellFormatter();
                while (dstIPStatsTable.getRowCount() > 0)
                    dstIPStatsTable.removeRow(0);
                StatsResult stats = (StatsResult) result;
                if (stats != null && stats.stats.length > 0) {
                    dstIPStatsTable.setWidget(0, 0, new StatsBarGraph(stats));
                } else {
                    while (dstIPStatsTable.getRowCount() > 0)
                        dstIPStatsTable.removeRow(0);
                    dstIPStatsTable.setHTML(0, 0, "No Destination IP stats currently stored in the database.");
                }
            }
        };

        nfseService.getDstIPStats(getStatsSensors(), getStatCount(), getStatUnits(), includeToday(),
                getStatsDirection(), callback);
    }

    private void dstPortStats() {

        ReportServiceAsync nfseService = (ReportServiceAsync) GWT.create(ReportService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.REPORT_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                FlexTable.FlexCellFormatter formatter = dstPortStatsTable.getFlexCellFormatter();
                while (dstPortStatsTable.getRowCount() > 0)
                    dstPortStatsTable.removeRow(0);
                StatsResult stats = (StatsResult) result;
                if (stats != null && stats.stats.length > 0) {
                    dstPortStatsTable.setWidget(0, 0, new StatsBarGraph(stats));
                } else {
                    while (dstPortStatsTable.getRowCount() > 0)
                        dstPortStatsTable.removeRow(0);
                    dstPortStatsTable.setHTML(0, 0, "No Destination Port Stats currently stored in the database.");
                }
            }
        };

        nfseService.getDstPortStats(getStatsSensors(), getStatCount(), getStatUnits(), includeToday(),
                getStatsDirection(), callback);
    }

    private int getStatCount() {
        int idx = this.statsTimeRangeListBox.getSelectedIndex();
        int count = 1;
        switch (idx) {
        case 0:
            count = 1;
            break;
        case 1:
            count = 7;
            break;
        case 2:
            count = 1;
            break;
        case 3:
            count = 2;
            break;
        case 4:
            count = 3;
            break;
        case 5:
            count = 1; // Calendar.YEAR
            break;
        }
        return count;
    }

    public int getStatsDirection() {
        int idx = statsDirectionListBox.getSelectedIndex();
        return idx;
    }

    public int[] getStatsSensors() {
        int[] sensors = { -1 };
        return sensors;
    }

    private int getStatUnits() {
        int idx = this.statsTimeRangeListBox.getSelectedIndex();
        int units = -1; // All Time
        switch (idx) {
        case 0:
        case 1:
            units = 5; // Calendar.DAY_OF_MONTH
            break;
        case 2:
        case 3:
        case 4:
            units = 2; // Calendar.MONTH
            break;
        case 5:
            units = 1; // Calendar.YEAR
            break;
        }
        return units;
    }

    public boolean includeToday() {
        return statsIncludeTodayCheckBox.isChecked();
    }

    private void protocolStats() {

        ReportServiceAsync nfseService = (ReportServiceAsync) GWT.create(ReportService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.REPORT_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                FlexTable.FlexCellFormatter formatter = protocolStatsTable.getFlexCellFormatter();
                while (protocolStatsTable.getRowCount() > 0)
                    protocolStatsTable.removeRow(0);
                StatsResult stats = (StatsResult) result;
                if (stats != null && stats.stats.length > 0) {
                    protocolStatsTable.setWidget(0, 0, new StatsBarGraph(stats));
                } else {
                    while (protocolStatsTable.getRowCount() > 0)
                        protocolStatsTable.removeRow(0);
                    protocolStatsTable.setHTML(0, 0, "No Protocol Stats currently stored in the database.");
                }
            }
        };
        int units = getStatUnits();
        int count = getStatCount();
        nfseService.getProtocolStats(getStatsSensors(), getStatCount(), getStatUnits(), includeToday(),
                getStatsDirection(), callback);
    }

    private void srcIPStats() {

        ReportServiceAsync nfseService = (ReportServiceAsync) GWT.create(ReportService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.REPORT_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                FlexTable.FlexCellFormatter formatter = srcIPStatsTable.getFlexCellFormatter();
                while (srcIPStatsTable.getRowCount() > 0)
                    srcIPStatsTable.removeRow(0);
                StatsResult stats = (StatsResult) result;
                if (stats != null && stats.stats.length > 0) {
                    srcIPStatsTable.setWidget(0, 0, new StatsBarGraph(stats));
                } else {
                    while (srcIPStatsTable.getRowCount() > 0)
                        srcIPStatsTable.removeRow(0);
                    srcIPStatsTable.setHTML(0, 0, "No Source IP stats currently stored in the database.");
                }
            }
        };

        nfseService.getSrcIPStats(getStatsSensors(), getStatCount(), getStatUnits(), includeToday(),
                getStatsDirection(), callback);
    }

    public void stats() {
        protocolStats();
        dstIPStats();
        srcIPStats();
        dstPortStats();
        if (includeToday())
            statsTimer.schedule(60000);
    }

}
